<!DOCTYPE html>
<head>
<meta charset="utf-8"/>
<meta name="timeout" content="long">
<title>Service Worker: Partitioned Cookies 3P Iframe</title>
<script src="partitioned-cookies-test-helpers.js"></script>
<script src="/resources/testharness.js"></script>
<script src="test-helpers.sub.js"></script>
</head>

<body>
<script>

promise_test(async t => {
  const script = './partitioned-cookies-3p-sw.js';
  const scope = './partitioned-cookies-3p-';
  const absolute_scope = new URL(scope, window.location).href;

  assert_false(
      document.cookie.includes('__Host-partitioned=123'),
      'DOM cannot access partitioned cookie');

  const reg = await service_worker_unregister_and_register(t, script, scope);
  await wait_for_state(t, reg.installing, 'activated');

  let retrieved_registrations =
        await navigator.serviceWorker.getRegistrations();
  let filtered_registrations =
    retrieved_registrations.filter(reg => reg.scope == absolute_scope);

  const next_message = worker_message_generator();

  // First test that the worker script started correctly and message passing
  // is enabled.
  filtered_registrations[0].active.postMessage({type: 'test_message'});
  const msg1 = await next_message();
  assert_true(msg1.ok, 'Message passing');

  // Test that the partitioned cookie is not available to this worker via HTTP.
  filtered_registrations[0].active.postMessage({type: 'echo_cookies_http'});
  const msg2 = await next_message();
  assert_true(msg2.ok, 'Get cookies');
  assert_false(
      msg2.cookies.includes('__Host-partitioned'),
      'Worker cannot access partitioned cookie via HTTP');
  assert_true(
      msg2.cookies.includes('unpartitioned'),
      'Worker can access unpartitioned cookie via HTTP');

  // Test that the partitioned cookie is not available to this worker via
  // CookieStore API.
  filtered_registrations[0].active.postMessage({type: 'echo_cookies_js'});
  const msg3 = await next_message();
  assert_true(msg3.ok, 'Get cookies');
  assert_false(
      msg3.cookies.includes('__Host-partitioned'),
      'Worker cannot access partitioned cookie via JS');
  assert_true(
      msg3.cookies.includes('unpartitioned'),
      'Worker can access unpartitioned cookie via JS');

  // Test that the partitioned cookie is not available to this worker in HTTP
  // requests from importScripts.
  filtered_registrations[0].active.postMessage({type: 'echo_cookies_import'});
  const msg4 = await next_message();
  assert_true(msg4.ok, 'Get cookies');
  assert_false(
      msg4.cookies.includes('__Host-partitioned'),
      'Worker cannot access partitioned cookie via importScripts');
  assert_true(
      msg4.cookies.includes('unpartitioned'),
      'Worker can access unpartitioned cookie via importScripts');
});

</script>
</body>
</html>
